﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Caching;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Localization;
using Volo.Abp.ObjectMapping;

namespace YunxSoft.Abp.LanguageManagement;

public class DatabaseLanguageProvider : ILanguageProvider
{
    public const string CacheKey = "AllLanguages";

    protected ILanguageRepository LanguageRepository { get; }

    protected IObjectMapper<LanguageManagementDomainModule> ObjectMapper { get; }

    protected IDistributedCache<LanguageListCacheItem> Cache { get; }

    public DatabaseLanguageProvider(ILanguageRepository languageRepository, IObjectMapper<LanguageManagementDomainModule> objectMapper, IDistributedCache<LanguageListCacheItem> cache)
    {
        LanguageRepository = languageRepository;
        ObjectMapper = objectMapper;
        Cache = cache;
    }

    public virtual async Task<IReadOnlyList<LanguageInfo>> GetLanguagesAsync()
    {
        return (await Cache.GetOrAddAsync(CacheKey, GetLanguageList)).Languages.OrderBy(x => x.CultureName).ToArray();
    }

    private async Task<LanguageListCacheItem> GetLanguageList()
    {
        var list = await LanguageRepository.GetListAsync(true);
        return new LanguageListCacheItem(ObjectMapper.Map<List<Language>, List<LanguageInfo>>(list));
    }
}